package com.gree.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gree.commom.enums.OrderStatus;
import com.gree.commom.enums.PayStatus;
import com.gree.commom.enums.PromTypeStatus;
import com.gree.commom.enums.SendStatus;
import com.gree.commom.result.BaseResult;
import com.gree.order.entity.Order;
import com.gree.order.entity.OrderGoods;
import com.gree.order.mapper.OrderGoodsMapper;
import com.gree.order.mapper.OrderMapper;
import com.gree.order.service.OrderService;
import com.gree.rpc.entity.Admin;
import com.gree.rpc.vo.CartResult;
import com.gree.rpc.vo.CartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
 
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderGoodsMapper orderGoodsMapper;

    @Value("${redis.order.increment}")
    private String redisOrderIncrement;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
   
    /**
     * 生成订单
     * @param admin
     * @param cartResult
     * @return
     */
    @Override
    public BaseResult orderSave(Admin admin, CartResult cartResult) {
        Order order = new Order();
        //订单编号
        String orderSn  = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now()) + getIncrementkey(redisOrderIncrement);
        order.setOrderSn(orderSn);
        //用户id
        order.setUserId(admin.getAdminId().intValue());
        //订单状态(未确认)
        order.setOrderStatus(OrderStatus.no_confirm.getStatus());
        //发货状态(未发货)
        order.setShippingStatus(SendStatus.no_pay.getStatus());
        //支付状态(未支付)
        order.setPayStatus(PayStatus.no_pay.getStatus());
        //商品总价
        order.setGoodsPrice(cartResult.getTotalPrice());
        //应付金额
        order.setOrderAmount(cartResult.getTotalPrice());
        //订单总价
        order.setTotalAmount(cartResult.getTotalPrice());
        //下单时间
        Long addTime = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
        order.setAddTime(addTime.intValue());
        int result = orderMapper.insert(order);

        if(result>0){
            List<OrderGoods> orderGoodsList = new ArrayList<>();
            List<CartVo> cartList = cartResult.getCartList();
            for (CartVo cartVo : cartList) {
                OrderGoods orderGoods = new OrderGoods();
                //订单id
                orderGoods.setOrderId(order.getOrderId());
                //商品id
                orderGoods.setGoodsId(cartVo.getGoodsId());
                //商品名称
                orderGoods.setGoodsName(cartVo.getGoodsName());
                //商品价格
                orderGoods.setMarketPrice(cartVo.getMarketPrice());
                //商品数量
                orderGoods.setGoodsNum(cartVo.getGoodsNum().shortValue());
                //订单方式
                orderGoods.setPromType(PromTypeStatus.normal.getStatus());
                //发货状态
                orderGoods.setIsSend(SendStatus.no_pay.getStatus());
                //添加订单商品信息
                orderGoodsList.add(orderGoods);
            }
            //批量添加订单商品信息
            result = orderGoodsMapper.insertOrderGoodsBatch(orderGoodsList);
            if(result>0){
               BaseResult baseResult = new BaseResult();
               baseResult.setMessage(orderSn);
               return  baseResult;
            }
        }
        return BaseResult.error();
    }

    /**
     * redis自增key
     * @return
     */
    private Long getIncrementkey(String key){
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key,redisTemplate.getConnectionFactory());
        long incrementKey = entityIdCounter.getAndIncrement();
        return incrementKey;
    }

    /**
     * 通过订单编号获取订单
     * @param orderSn
     * @return
     */
    @Override
    public Order selectOrderByOrderSn(String orderSn) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_sn",orderSn);
        Order order = orderMapper.selectOne(queryWrapper);
        return order == null? null:order;
    }
}
